<?php

namespace app\adminapi\controller;

use think\Controller;
use think\Request;

class Admin extends BaseApi
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
				$param = input();
				$where = [];
				if(!empty($param['keyword'])){
						$keyword = $param['keyword'];
						$where['t1.username'] = ['like', "%$keyword%"];
				}								
				$list = \app\common\model\Admin::alias('t1')
				->join('pyg_role t2','t1.role_id=t2.id','left')
				->field('t1.id id,username,email,nickname,last_login_time,status,t2.role_name')
				->where($where)->paginate(2);
												
				$this->ok($list);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
			$data = \app\common\model\Admin::find($id);
      $this->ok($data);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
				if($id == 1){
						$this->fail('无法修改超级管理员的信息', 401,'');
				}  
				$params = input();
				if(!empty($params['type']) && $params['type'] == 'reset_pwd'){
						$password = encrypt_password('123456');
						$res = \app\common\model\Admin::update(['password'=>$password], ['id' => $id ], true);
						if(empty($res)){
								$this->fail('重置失败', 402);
						} 				
				} else {
						$validate = $this->validate($params, [
								'email|邮箱' => 'email',
								'role_id|所属角色' => 'integer|gt:0',
								'nickname|昵称' => 'max:50',
						]);
						if($validate !== true){
								$this->fail($validate, 401,'');
						}				
						unset($params['username']);
						unset($params['password']);
						$result = \app\common\model\Admin::update($params, ['id' => $id ], true);
						if(empty($result)){
								$this->fail('修改失败', 402,'');
						} 									
				}
				$data = \app\common\model\Admin::field('id,username,email,nickname,last_login_time,status,role_id')->find($id);
        $this->ok($data);												
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if($id == 1){
					$this->fail('不能删除超级管理员', 402,'');				
				}
				// if($id == input('id')){
    //         $this->fail('不能删除自己', 401,'');
    //     }				
				\app\common\model\Admin::destroy($id);
				$data = input();
				$this->ok($data);
    }
}
